<?php
/**
 * 媒资上线管理
 * @author liangpan
 */
include_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'public.class.php';
class nl_c2_task extends nl_public
{
	static $base_table='nns_mgtvbk_c2_task';
	static $arr_filed = array(
			'nns_id',
			'nns_type',
			'nns_name',
			'nns_ref_id',
			'nns_action',
			'nns_status',
			'nns_create_time',
			'nns_modify_time',
			'nns_org_id',
			'nns_category_id',
			'nns_src_id',
			'nns_all_index',
			'nns_clip_task_id',
			'nns_clip_date',
			'nns_op_id',
			'nns_epg_status',
			'nns_ex_url',
			'nns_file_path',
			'nns_file_size',
			'nns_file_md5',
			'nns_cdn_policy',
			'nns_epg_fail_time',
			'nns_message_id',
	        'nns_is_group',
	        'nns_weight',
	        'nns_cp_id',
			'nns_cdn_fail_time',
			'nns_notify_third_state',
            'nns_queue_execute_url',
            'nns_cdn_import_id',//cdn注入id xinxin.deng 2018/3/2 14:52
	);
	
	/**
	 * 查询cdn_epgde 终态信息
	 * @param object $dc 数据库对象
	 * @param array|string $mix_id  混合guid 主媒资guid | 分集guid | 片源 guid
	 * @param string $sp_id 运营商id
	 * @param string $type 类型  video 主媒资 | index 分集 | media 片源
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @authorliangpan
	 * @date 2015-12-25
	 */
	static public function query_end_state($dc,$mix_id,$sp_id,$type)
	{
		$str_sql = is_string($mix_id) ? $mix_id : implode("','", $mix_id);
		if(empty($str_sql))
		{
			return self::return_data(1,'id为空');
		}
		switch ($type)
		{
			case 'video':
				$sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " . 
						" nns_ref_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
				break;
			case 'index':
				$sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " . 
						" nns_src_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
				break;
			case 'media':
				$sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " .
						" nns_src_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
				break;
			default:
				return self::return_data(1,'没有此类型');
		}
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok',$result);
	}

	
	static public function query_c2_exsist($dc,$type,$mix_id,$sp_id)
	{
		$str_sql = is_string($mix_id) ? $mix_id : implode("','", $mix_id);
		if(empty($str_sql))
		{
			return self::return_data(1,'id为空');
		}
		switch ($type)
		{
			case 'video':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'index':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'media':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'live':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'live_index':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'live_media':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			case 'playbill':
				$sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
				break;
			default:
				return self::return_data(1,'没有此类型');
		}
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok',$result);
	}
	
/**
	 * 添加CDN直播频道队列
	 * @param object $dc 数据库对象
	 * @param array $params 数据数组
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-09-24
	 */
	static public function add($dc,$params)
	{
		$params = self::make_nns_pre($params);
		if(!isset($params['nns_id']) || strlen($params['nns_id'])<1)
		{
			$params['nns_id'] = np_guid_rand();
		}
		$date_time = date("Y-m-d H:i:s");
		if(!isset($params['nns_create_time']) || strlen($params['nns_create_time'])<1)
		{
			$params['nns_create_time'] = $date_time;
		}
		if(!isset($params['nns_modify_time']) || strlen($params['nns_modify_time'])<1)
		{
			$params['nns_modify_time'] = $date_time;
		}
		$params = self::except_useless_params(self::$arr_filed, $params);
		if(empty($params))
		{
			return self::return_data(1,'参数为空');
		}
		$sql = self::make_insert_sql(self::$base_table, $params);
		$result = nl_execute_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok');
	}
	
	/**
	 * 修改CDN直播频道队列
	 * @param object $dc 数据库对象
	 * @param array $params 数据数组
	 * @param string $nns_id GUID
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-09-24
	 */
	static public function edit($dc,$params,$nns_id)
	{
		$params = self::make_nns_pre($params);
		if((is_string($nns_id) && strlen($nns_id) <1) || (is_array($nns_id) && !empty($nns_id)))
		{
		    return self::return_data(1,'CDN直播频道队列guid为空');
		}
		$params = self::except_useless_params(self::$arr_filed, $params);
		if(empty($params))
		{
			return self::return_data(1,'参数为空');
		}
		if(!isset($params['nns_modify_time']) || strlen($params['nns_modify_time'])<1)
		{
			$params['nns_modify_time'] = date("Y-m-d H:i:s");
		}
		$sql = self::make_update_sql(self::$base_table, $params,array('nns_id'=>$nns_id));
		$result = nl_execute_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok:'.$sql);
	}
	
	/**
	 * 依据条件查询分集信息
	 * @param $dc
	 * @param $params
	 * @return array
	 */
	static public function query_by_condition_v2($dc, $params)
	{
	    $params = self::except_useless_params(self::$arr_filed, $params);
	    if (!is_array($params) || empty($params))
	    {
	        return self::return_data(1, '查询条件为空不允许查询');
	    }
	    $sql = self::make_query_sql(self::$base_table, $params);
	    $result = nl_query_by_db($sql, $dc->db());
	    if (!$result)
	    {
	        return self::return_data(1, '数据库查询失败,sql:' . $sql);
	    }
	    $result = (isset($result) && !empty($result)) ? $result : null;
	    return self::return_data(0, 'OK' . $sql, $result);
	}
	
	static public function query($dc,$arr_params=null,$page_info=null)
	{
		
	}
	
	/**
	 * guid查询C2 表的 数据
	 * @param unknown $dc
	 * @param unknown $nns_id
	 * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据'), 
	 */
	static public function query_data_by_id($dc,$nns_id)
	{
	    $nns_id = is_array($nns_id) ? $nns_id : array($nns_id);
	    if(empty($nns_id))
	    {
	        return self::return_data(1,"参数ID 为空");
	    }
	    $nns_id = array_values($nns_id);
		$sql="select * from " . self::$base_table . " where nns_id in('".implode("','", $nns_id)."')";
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok:'.$sql,$result);
	}
	
	/**
	 * 查询单个列表
	 * @param object $dc 数据库对象
	 * @param string $nns_id guid
	 * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2016-09-24
	 */
	static public function query_by_id($dc,$nns_id)
	{
		$sql = "select * from " . self::$base_table . " where nns_id='{$nns_id}' limit 1";
		$result = nl_query_by_db($sql, $dc->db());
		if(!$result)
		{
			return self::return_data(1,'数据库查询失败,sql:'.$sql);
		}
		$result = (isset($result[0]) && !empty($result[0])) ? $result[0] : null;
		return self::return_data(0,'OK:'.$sql,$result);
	}
	/**
	 * 取消C2任务队列
	 * @param object $dc
	 * @param array $params
	 * @param array $where
	 * @author zhiyong.luo
	 */
	static public function cancel_c2_task($dc,$params,$where)
	{
		if(!is_array($params) || empty($params) || !is_array($where) || empty($where))
		{
			return self::return_data(1,'参数错误');
		}
		$set_str = '';
		foreach ($params as $k=>$val)
		{
			$set_str .= "{$k} = '{$val}',";
		}
		$set_str = rtrim($set_str,",");
		
		$where_str = '';
		foreach ($where as $key=>$value)
		{
			if($key === 'in' && !empty($value) && is_array($value))
			{
				foreach ($value as $key_in => $in_value)
				{
					if(is_array($in_value) && !empty($in_value))
					{
						$in_ids = implode("','", $in_value);
						$where_str .= " {$key_in} in ('{$in_ids}') AND ";
					}
				}
			}
			elseif(!empty($value) || $value == '0')
			{
				$where_str .= " {$key} = '{$value}' AND ";
			}
		}
		$where_str = rtrim($where_str," AND ");
		if(!empty($where_str))
		{
			$where_str = " WHERE " . $where_str;
		}
		$sql = "UPDATE " . self::$base_table . " SET {$set_str} {$where_str}";
		$result = nl_execute_by_db($sql, $dc->db());
		if($result === false)
		{
			return self::return_data(1,'mysql execute failed');
		}
		else
		{
			return self::return_data(0,'OK');
		}
	}
	
	/**
	 * 消息查询
	 * @param unknown $dc
	 * @param unknown $message_id
	 * @param unknown $cp_id
	 */
	static public function query_message_by_message_id($dc,$message_id,$sp_id,$video_type)
	{
	    $str_temp = (is_array($sp_id) && !empty($sp_id)) ? " and nns_org_id in ('" . implode("','", $sp_id) . "') " : " and nns_org_id = '{$sp_id}' ";
	    $sql="select * from " . self::$base_table . " where nns_message_id='{$message_id}' and nns_type='{$video_type}' {$str_temp} limit 1" ;
	    $result = nl_query_by_db($sql, $dc->db());
	    if(!$result)
	    {
	        return self::return_data(1,'消息队列查询失败'.$sql);
	    }
	    $result = (isset($result[0]) && !empty($result[0]) && is_array($result[0])) ? $result[0] : null;
	    return self::return_data(0,'ok',$result);
	}
	
	/**
	 * 
	 * @param unknown $dc
	 * @param unknown $nns_id
	 */
	static public function edit_cdn_fail_time($dc,$nns_id)
	{
	    $date = date("Y-m-d H:i:s");
	    if(!(is_string($nns_id) && strlen($nns_id) <1) || !(is_array($nns_id) && !empty($nns_id)))
		{
		    return self::return_data(1,'CDN直播频道队列guid为空');
		}
		$str_id = (is_array($nns_id)) ? implode("','", $nns_id) : $nns_id;
		$sql="update " . self::$base_table . " set nns_cdn_fail_time=nns_cdn_fail_time+1,nns_modify_time='{$date}',nns_state=-1 where nns_id in('{$str_id}')";
		$result = nl_execute_by_db($sql, $dc->db());
		if(!$result)
		{
		    return self::return_data(1,'数据库执行失败'.$sql);
		}
		return self::return_data(0,'ok '.$sql);
	}
	
	
	/**
	 *
	 * @param unknown $dc
	 * @param unknown $nns_id
	 */
	static public function edit_cdn_fail_time_v2($dc,$nns_id)
	{
	    $date = date("Y-m-d H:i:s");
	    if(!(is_string($nns_id) && strlen($nns_id) <1) || !(is_array($nns_id) && !empty($nns_id)))
	    {
	        return self::return_data(1,'CDN直播频道队列guid为空');
	    }
	    $str_id = (is_array($nns_id)) ? implode("','", $nns_id) : $nns_id;
	    $sql="update " . self::$base_table . " set nns_cdn_fail_time=nns_cdn_fail_time+1,nns_modify_time='{$date}' where nns_id in('{$str_id}')";
	    $result = nl_execute_by_db($sql, $dc->db());
	    if(!$result)
	    {
	        return self::return_data(1,'数据库执行失败'.$sql);
	    }
	    return self::return_data(0,'ok '.$sql);
	}
	
	/**
	 * 根据条件获取
	 * @param object $dc
	 * @param array $params
	 * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 */
	static public function query_by_condition($dc,$params,$since = '',$num = '',$str_order='')
	{
	    if (empty($params) || !is_array($params))
	    {
	        return self::return_data(1,'参数错误');
	    }
	    $where = '';
	    foreach ($params as $key=>$val)
	    {
	        $where .= "$key='{$val}' and ";
	    }
	    $where = rtrim($where," and ");
	    if(!empty($where))
	    {
	        $where = " where " . $where;
	    }
	    
	    if(!empty($str_order) && strlen($str_order) >0)
	    {
	        $where .= " {$str_order} ";
	    }
	
	    if (strlen($since) > 0 && strlen($num) > 0)
	    {
	        $limit = ' limit ' . $since . ',' . $num;
	    }
	    else
	    {
	        $limit = '';
	    }
	    $sql = "select * from " . self::$base_table . $where . $limit;
	    $result = nl_query_by_db($sql, $dc->db());
	    if(!is_array($result))
	    {
	        return self::return_data(1,'没有数据'.$sql);
	    }
	    return self::return_data(0,'ok',$result);
	}
	
	/**
	 * 删除日志  通过 状态和日期，目前只支持删除节目单
	 * @param unknown $dc
	 * @param unknown $sp_id
	 * @param unknown $str_date
	 * @param string $flag_cdn
	 * @param string $epg_state
	 */
	static public function del_by_date_and_state($dc,$sp_id,$str_date,$flag_cdn =true ,$epg_state=true)
	{
	    if(strlen($sp_id) <1)
	    {
	        return self::return_data(1,'删除的$sp_id为空');
	    }
	    if(strlen($str_date) <1)
	    {
	        return self::return_data(1,'删除的创建日期为空');
	    }
	    if(!$flag_cdn && !$epg_state)
	    {
	        return self::return_data(1,'CDN['.var_export($flag_cdn,true).']、EPG['.var_export($epg_state,true).']状态必须要有一个为终态');
	    }
	    $sql = "delete from " . self::$base_table . " where nns_org_id='{$sp_id}' and nns_type='playbill' ";
	    if($flag_cdn)
	    {
	        $sql .= " and nns_status='0' ";
	    }
	    if($flag_cdn)
	    {
	        $sql .= " and nns_epg_status='99' ";
	    }
	    $sql.=" and nns_create_time <='{$str_date}' ";
	    $result = nl_execute_by_db($sql, $dc->db());
	    if(!$result)
	    {
	        return self::return_data(1,'数据库执行失败'.$sql);
	    }
	    return self::return_data(0,'ok '.$sql);
	}
	/**
     * 定时器：业务逻辑层SQL---按条件获取注入CDN的任务
     * @param object $dc DC
     * @param $params array(
     *                    'key'=>'value',
     *                    'less_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'more_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                     'not_in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                )
     * @param int $limit 条数
     * @param $str_group group by
     * @param $str_order order by
     * @return array
     */
	static public function timer_get_c2_task($dc,$params,$limit=1,$str_group='',$str_order='')
    {
        $arr_where = self::__build_where($params);
        if($arr_where['ret'] != '0')
        {
            $where = '';
        }
        else
        {
            $where = $arr_where['data_info'];
        }

        if(!empty($str_group) && strlen($str_group) > 0)
        {
            $where .= " {$str_group} ";
        }

        if(!empty($str_order) && strlen($str_order) > 0)
        {
            $where .= " {$str_order} ";
        }

        if (strlen($limit) > 0)
        {
            $limit = ' limit ' . $limit;
        }
        else
        {
            $limit = '';
        }
        $sql = "select * from " . self::$base_table . $where . $limit;
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败：'.$sql);
        }
        return self::return_data(0,'ok',$result);
    }

    /**
     * 创建where条件
     * @param $params
     * @return array array(
     *                    'key'=>'value',
     *                    'less_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'more_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                     'not_in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                )
     * @return array
     */
    static public function __build_where($params)
    {
        $where = '';
        if (empty($params) || !is_array($params))
        {
            return self::return_data(1,'没有where请求参数');
        }
        foreach ($params as $key=>$val)
        {
            switch ($key)
            {
                case 'less_than':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k}<='{$v}' and ";
                        }
                    }
                    break;
                case 'more_than':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k}<='{$v}' and ";
                        }
                    }
                    break;
                case 'in':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k} in ('" . implode("','",$v) . "') and ";
                        }
                    }
                    break;
                case 'not_in':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k} not in ('" . implode("','",$v) . "') and ";
                        }
                    }
                    break;
                default:
                    $where .= "{$key}='{$val}' and ";
                    break;
            }

        }
        $where = rtrim($where," and ");
        if(empty($where))
        {
            return self::return_data(1,'没有where请求参数');
        }
        return self::return_data(0,''," where " . $where);
    }

    /**
     * 依据条件查询主媒资信息
     * @param $dc
     * @param $sql
     * @return array
     */
    static public function query_by_sql($dc, $sql)
    {
        $result = nl_query_by_db($sql, $dc->db());
        if (!$result)
        {
            return self::return_data(1, '数据库查询失败,sql:' . $sql);
        }
        $result = (isset($result) && !empty($result)) ? $result : null;
        return self::return_data(0, 'OK' . $sql, $result);
    }



}